/**
 * 
 */
package soa.security.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.io.IOUtils;

/**
 * @author CreGu
 *
 */
public class JaxbUtils {

	@SuppressWarnings("unchecked")
	public static <T> T xml2Object(String xml, Class<T> clazz) throws Exception {
		InputStream is = null;
		JAXBContext context;
		try {
			is = new ByteArrayInputStream(xml.getBytes("UTF-8"));
			context = JAXBContext.newInstance(clazz);

			Unmarshaller shaller = context.createUnmarshaller();
			Object obj = shaller.unmarshal(is);

			return (T) obj;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("格式错误");
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	public static <T> String object2Xml(Object obj, Class<T> clazz)
			throws Exception {
		StringWriter sw = new StringWriter();
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(clazz);
			Marshaller shaller = context.createMarshaller();
			shaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			shaller.marshal(obj, sw);
			return sw.toString();
		} catch (Exception e) {
			throw e;
		} finally {
			IOUtils.closeQuietly(sw);
		}
	}
}
